package com.example.springbootmodel.jsonData.controller;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;

/**
 * @program: springbootmodel
 * @description: 返回Json数据工具类
 * @author: yang
 * @version: 1.0
 * @create: 23/7/27 17:29
 **/
@Slf4j
@ResponseBody
@Controller("jsonDataController")
@RequestMapping(value = "/jsonData")
public class JsonDataController {

    /***
     * @description: 根据文件名称来返回对应的json数据
     * @param: fileName
     * @return: com.alibaba.fastjson.JSONObject
     * @author: ym
     * @date: 23/7/27 17:38
     */
    @RequestMapping(value="/getJsonDataByFileName")
    public JSONObject getJsonDataByFileName(String fileName) throws IOException {
        return JSONObject.parseObject(new ClassPathResource(String.format("templates/json/%s.json",fileName))
                        .getInputStream(), StandardCharsets.UTF_8, JSONObject.class);
    }

    /***
     * @description: 根据路径来返回对应的json数据
     * @param: path
     * @return: com.alibaba.fastjson.JSONObject
     * @author: ym
     * @date: 23/7/27 17:50
     */
    @PostMapping(value="/getJsonDataByFilePath")
    public JSONObject getJsonDataByFilePath(String path) throws IOException {
        return JSONObject.parseObject(Files.newInputStream(Paths.get(path)), StandardCharsets.UTF_8, JSONObject.class);
    }

}
